import { Plugin } from 'siyuan'
import { setupEventListeners } from './docUtils'
import { MenuManager } from './menuManager'
import { EventHandlers } from './eventHandlers'

/**
 * 插件管理器
 * 负责插件的初始化和管理
 */
export class PluginManager {
  private plugin: Plugin
  private eventHandlers: EventHandlers
  private removeEventListeners: (() => void) | null = null

  constructor(plugin: Plugin, eventHandlers: EventHandlers) {
    this.plugin = plugin
    this.eventHandlers = eventHandlers
  }

  /**
   * 初始化插件
   */
  init() {
    this.setupTopBar()
    this.setupEventListeners()
  }

  /**
   * 设置顶栏按钮
   */
  private setupTopBar() {
    this.plugin.addTopBar({
      icon: 'iconEmoji',
      title: '文章发布工具',
      callback: (event: MouseEvent) => {
        MenuManager.showMainMenu(event, {
          onShowForm: this.eventHandlers.showTestForm,
          onLoadDoc: this.eventHandlers.loadCurrentDoc,
          onOptimizeTitle: this.eventHandlers.optimizeTitle,
          onShowHelp: this.eventHandlers.showHelp,
          onShowAbout: this.eventHandlers.showAbout
        })
      }
    })
  }

  /**
   * 设置事件监听器
   */
  private setupEventListeners() {
    this.removeEventListeners = setupEventListeners({
      onBlockIconClick: this.eventHandlers.onBlockIconClick
    })
    console.log('事件监听器设置完成')
  }

  /**
   * 清理资源
   */
  cleanup() {
    if (this.removeEventListeners) {
      this.removeEventListeners()
      this.removeEventListeners = null
    }
  }
}
